package org.tulkas.test.robot;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.LogManager;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tulkas.robot.base.FlusherManager;
import org.tulkas.robot.base.GlobalConfig;
import org.tulkas.robot.http.ClientManager;
import org.tulkas.util.EncodeUtil;
import org.tulkas.util.FileUtil;

/**
 * @author <a href="mailto:tulkas.web@gmail.com">Tulkas</a>
 *
 */
public class TulkasCase {
	private static Logger logger = null;

	private static boolean logInitilaized = false;

	static {
		if (!logInitilaized) {
			try {
				InputStream is = TulkasCase.class
						.getResourceAsStream("/logging.properties");
				if (is != null) {
					LogManager.getLogManager().readConfiguration(is);
					is.close();
					logger = LoggerFactory.getLogger(TulkasCase.class);
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			logInitilaized = true;
		}
	}

	@Rule
	public TestName testName = new TestName();

	@Before
	public void logBefore() throws Exception {
		logger.debug("=================TestCase " + testName.getMethodName()
				+ " Begin===============");
	}

	@After
	public void logAfter() throws Exception {
		ClientManager.getInstance().destroy();
		logger.debug("*****************TestCase " + testName.getMethodName()
				+ " End  ***************");
	}

	@BeforeClass
	public static void classSetUp() throws Exception {
		String dirStr = System.getProperty("java.io.tmpdir");
		File rootDir = new File(dirStr, EncodeUtil.uuid());
		System.setProperty("tulkas.robot.home", FileUtil.trimFilePath(rootDir
				.getAbsolutePath()));
	}

	@AfterClass
	public static void classTearDown() throws Exception {
		clearData();
		destroyManagers();
		System.clearProperty("tulkas.robot.home");
	}

	public static void clearData() {
		File dir = new File(GlobalConfig.getInstance().getDataPath());
		if (dir.exists()) {
			FileUtil.delTree(dir.getAbsolutePath());
		}
	}

	public static void destroyManagers() {
		ClientManager.getInstance().destroy();
		FlusherManager.getInstance().destroy();
		GlobalConfig.getInstance().destroy();
	}
}
